package com.boot.configstatistical.topic;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author songlin.an
 * @className Test
 * @description 配置导出控制器
 * @date 2023/5/13 20:20
 **/
@RestController
public class ExportController {
    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    @RequestMapping(value = "/exportTopicConfig", method = RequestMethod.GET)
    public void exportMemberList(HttpServletResponse response) {
        JSONObject json = new JSONObject();
        json.put("projectCode", "dmall_payment_system");
        json.put("appCode", "pay-channel-cbestpay");
        json.put("currentPage", 1);
        json.put("pageSize", 10);
        json.put("env", "prod");
        String url = "http://cmdb-api.dmall.com/api/dmg/topic/permission/list?versionType=PRO";
        HttpPost httpPost = new HttpPost(url);
        BasicHeader header = new BasicHeader("Cookie","dhrUserId=9157561; appname=cloud; username=songlin.an; GALAXY_OFFLINE_CLIENT_WEB_VERSION_9e74bd830361046daa00798aa282f1fe=10; loginType=account; login_user_name=%E5%AE%89%E6%9D%BE%E6%9E%97; login_type=vpn; login_dmall_id=songlin.an; return_url=http%3A//cloud.dmall.com/%23index/dmalltp/releaseConfig%3AversionType%3DPRO%26level%3D6%26sysCode%3Ddmall-payment-coop%26Code%3Dpay-channel-applepay-prod%26appName%3Dpay-channel-applepay-prod%26projectCode%3Ddmall_payment_system%26appCode%3Dpay-channel-applepay-prod; login_token=Bearer%20eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2ODQ0NjMzODQ3MDQsImV4cCI6MTY4NTA2ODE4NDcwNCwiaXNzIjoia2VuIiwiZGF0YSI6eyJ1c2VyX2luZm8iOnsidXNlcl9pZCI6OTE1NzU2MSwidXNlcl9jb2RlIjoic29uZ2xpbi5hbiIsInVzZXJfbmFtZSI6Ilx1NWI4OVx1Njc3ZVx1Njc5NyIsInBob25lIjoiIiwiZW1haWwiOiJzb25nbGluLmFuQGRtYWxsLmNvbSIsImhyc19pZCI6ODY0Mzk2MSwiaHJtc19pZCI6MTAwMDEzMDg0MSwidXNlcl9ubyI6IjEwMDAwMTI1OCJ9LCJsb2dpbl90aW1lIjoxNjg0NDYzMzg0NzA0fX0.yZsQM9BrWhmQ84pvDgZCbrFoF5Mx0NY0EGqNJm_3mjw; envRootDomain=dmall.com; aladdin_route_key=2d5769630507d04f13b719f4a587bf9e; zone=gz01; UYBFEWAEE=EA970CF573B5F3A0725F0C06D37B02DBC3DD18CF3A4AD3A8B5D9EDA5542436333E0994E5D822F51EF3EA220922DFC1C9038C46D1A381F580A6F9A256C04A5CF5A981510C3196C82723F90D29F9E2ED8C; login_no=\"RGQxMDAwMDEyNThfMTU1MzM3ODM5NTc=\"; wm_menu_id=menu_1114; signature=0efbf7f86bc0888b16fcd7e5c3b6902b; timestamp=1684748611");
                httpPost.setHeader(header);
        CloseableHttpClient client = HttpClients.createDefault();
        StringEntity entity = new StringEntity(json.toString(), "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try {
            setExcelRespProp(response, "TOPIC配置统计表");
            HttpResponse result = client.execute(httpPost);
            if (result.getStatusLine().getStatusCode() == 200) {
                TopicConfigResponse testResponse = JSON.parseObject(EntityUtils.toString(result.getEntity(), "UTF-8"), TopicConfigResponse.class);
                List<TopicConfig> resultList = testResponse.getData().getResult();
                for (TopicConfig topicConfig : resultList) {
                    if (topicConfig.getRightType() == 2) {
                        topicConfig.setTopicType("消费者");
                    } else {
                        topicConfig.setTopicType("生产者");
                    }
                }
                EasyExcel.write(response.getOutputStream())
                        .head(TopicConfig.class)
                        .excelType(ExcelTypeEnum.XLSX)
                        .sheet("TOPIC配置统计表")
                        .doWrite(resultList);
                System.out.println(JSONObject.toJSONString(result));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

    }

}
